<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\JasminumHotelReservations\Controllers;

use Gotcha\App\Extensions\GotchaCulturesExtension;
use Gotcha\App\Extensions\GotchaErrorsExtension;
use Gotcha\App\Extensions\GotchaLogsExtension;
use Gotcha\App\Framework\Controller;
use Gotcha\App\Types\String;
use GotchaDatabase\GotchaSettingsQuery;
use GotchaDatabase\JasminumHotelReservations;

class DefaultController extends Controller {
    public function getRoomColors() {
        $roomTypes = new \ReflectionClass('Modules\JasminumHotelReservations\Enums\RoomColors');
        return $roomTypes->getConstants();
    }

    public function getRoomTypes() {
        $roomTypes = new \ReflectionClass('Modules\JasminumHotelReservations\Enums\RoomTypes');
        return $roomTypes->getConstants();
    }

    public function Send() {
        // Validation
        if (empty($_POST['ReturnURL']) || !isset($_POST['ReturnURL'])) {
            die('Error.');
        }

        if (empty($_POST['RoomType']) && !isset($_POST['RoomType']) || empty($_POST['Firstname']) || empty($_POST['Lastname']) || empty($_POST['Email']) || empty($_POST['Phone']) || empty($_POST['DateFrom']) || empty($_POST["DateTo"])) {
            var_dump($_POST);
            die();
            header('Location: '.GOTCHA_BASE_PATH.$_POST['ReturnURL'].'?error=1#notification');
            exit;
        }

        // Check if sent room color/type exists
        $roomColors = self::getRoomColors();
        $roomTypes = self::getRoomTypes();

        if (!in_array($_POST['RoomType'], $roomTypes)) {
            header('Location: '.GOTCHA_BASE_PATH.$_POST['ReturnURL'].'?error=2#notification');
            exit;
        }

        if (!filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL)) {
            header('Location: '.GOTCHA_BASE_PATH.$_POST['ReturnURL'].'?error=3#notification');
            exit;
        }

        // If we get that far, data passed validation
        $reservations = new JasminumHotelReservations();

        try {
            $reservations->setFirstname($_POST['Firstname']);
            $reservations->setLastname($_POST['Lastname']);
            $reservations->setEmail($_POST['Email']);
            $reservations->setPhone($_POST['Phone']);
            $reservations->setDateFrom($_POST['DateFrom']);
            $reservations->setDataTo($_POST['DateTo']);

            // Set room
            $reservations->setRoomColor(array_search($_POST['RoomColor'], $roomColors));
            $reservations->setRoomType(array_search($_POST['RoomType'], $roomTypes));

            $reservations->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        // Mail
        $mail = new \PHPMailer();

        $mail->IsSMTP(); // Use SMTP
        $mail->SMTPDebug = 0;
        $mail->SMTPAuth = true; // Use SMTP authentication
        $mail->SMTPSecure = "tls";
        $mail->Host = 'mail.restauracja-jasminum.pl';
        $mail->Port = 587;
        // $mail->Username = 'automat@codenova.drl.pl';
        $mail->Username = 'automat@restauracja-jasminum.pl';
        // $mail->Password = 'automat1';
        $mail->Password = ';Z;;gF(lBl++';
        $mail->CharSet = 'UTF-8';

        $mail->SetFrom('automat@restauracja-jasminum.pl', 'Restauracja Jasminum - Automat');
        $mail->Subject = 'Rezerwacja';
        $mail->MsgHTML('<body><h1>Nowa rezerwacja</h1><p>Na stronie Siedlisko Jasminum wypełniono nową rezerwację. Poniżej znajdują się szczegóły.</p><table cellpadding="2" cellspacing="2"><tbody><tr><td><b>Typ pokoju:</b></td><td>'.array_search($_POST['RoomType'], $roomTypes).'</td></tr><tr><td><b>Imię i nazwisko: </b></td><td>'.$_POST['Firstname'].' '.$_POST['Lastname'].'</td></tr><tr><td><b>Adres email:</b></td><td>'.$_POST['Email'].'</td></tr><tr><td><b>Numer telefonu:</b></td><td>'.$_POST['Phone'].'</td></tr><tr><td><b>Data od:</b></td><td>'.$_POST['DateFrom'].'</td></tr><tr><td><b>Data do:</b></td><td>'.$_POST['DateTo'].'</td></tr></tbody></table><p><small>Wiadomość wygenerowana automatycznie - nie odpowiadaj na nią.</small></p></body>');

        // Retrieve recipient e-mail
        $settings = GotchaSettingsQuery::create()
                    ->filterByStrongName('ReservationsHotelMail')
                        ->findOne();

        // It is possible to add multiple emails
        // so be prepared!
        $mails = explode(';', $settings->getValue());

        foreach($mails as $mailAddress) {
            if($mailAddress != '') {
                $mail->AddAddress($mailAddress);
            }
        }

        if (!$mail->Send()) {
            GotchaLogsExtension::createNewLogEntry(new String($mail->ErrorInfo));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_SENDING_MAIL'))));
            exit;
        }

        // Data is saved, return a view
        header('Location: '.GOTCHA_BASE_PATH.'/JasminumHotelReservations/Congratulations');
        exit;
    }

    public function Congratulations() {
        parent::View();
    }
}